import $ from "jquery";
import { PageViewModel } from "./page-context";
import { DevicePartResponse } from "../../tyeps/device-part-response";

export default async function createTableAsync(viewModel: PageViewModel) {
  const parts: DevicePartResponse[] = [];
  viewModel.deviceMaintenanceList.map((deviceItem) => {
    if (deviceItem.parts.length > 0) {
      for (let index = 0; index < deviceItem.parts.length; index++) {
        const currentPart = deviceItem.parts[index];
        currentPart.devicePartName =
          deviceItem.device.deviceName + "-" + currentPart.devicePartName;
        parts.push(currentPart);
      }
    }
  });

  const isMixingMachine = viewModel.processName === "mixing";
  let index = 0;
  const partInfos = parts.map((item) => {
    let path = "";

    if (isMixingMachine) {
      path = "/cardboards/mixing?";
    } else {
      path = "/cardboards/pulping?";
    }

    const link =
      process.env.SELF_URL +
      path +
      "deviceId=" +
      encodeURIComponent(item.deviceMaintenanceId);
    index++;
    return {
      index: index,
      partName: item.devicePartName,
      maintenanceStatus: item.maintenanceStatus,
      currentLifetime: item.currentLifetime,
      accumulatedDowntime: item.accumulatedDowntime,
      economicLifetimeThreshold: item.economicLifetimeThreshold,
      url: {
        link: link,
        descriptor: `跳转到${item.devicePartName}设备`,
      },
    };
  });

  $("#partTable").bootstrapTable({
    columns: [
      {
        field: "index",
        title: "序号",
      },
      {
        field: "partName",
        title: "部件名称",
      },
      {
        field: "maintenanceStatus",
        title: "部件状态",
      },
      {
        field: "currentLifetime",
        title: "当前寿命",
      },
      {
        field: "economicLifetimeThreshold",
        title: "经济寿命",
      },
      {
        field: "accumulatedDowntime",
        title: "停机寿命",
      },
      {
        field: "url",
        title: "#",
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        formatter: (url: any) => {
          return `<a href="${url.link}">${url.descriptor}</a>`;
        },
      },
    ],
    data: partInfos,
  });
  $("#partTable").bootstrapTable("hideLoading");
}
